//
//  JwLanguager.m
//  JwPack
//
//  Created by 陈警卫 on 2024-08-07.
//

#import "JwLanguager.h"

/// 语言存储key
#define kJwLanguagerSaveKey @"kJwLanguagerSaveKey"

@interface JwLanguager ()

/// 当前语言 默认系统语言
@property (nonatomic, strong) NSString *currentLanguage;

@end

@implementation JwLanguager

/// 单例
+ (JwLanguager *)shared {
    static JwLanguager *sharedObject;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        sharedObject = [[JwLanguager alloc] initShared];
    });
    return sharedObject;
}

- (instancetype)init {
    return [[self class] shared];
}

- (instancetype)initShared {
    self = [super init];
    if (self) {
        [self setupData];
    }
    return self;
}

- (void)setupData {
    
    self.enable = YES;
    self.searchEn = YES;
    
    if (![[NSUserDefaults standardUserDefaults] objectForKey:kJwLanguagerSaveKey]) {
        NSString *language = [NSLocale preferredLanguages].firstObject;
        [[NSUserDefaults standardUserDefaults] setObject:language forKey:kJwLanguagerSaveKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        self.currentLanguage = language;
    }
}

/// 设置当前语言
- (void)setupCurrentLanguage:(NSString *)language {
    if ([self.languageCans containsObject:language]) {
        [[NSUserDefaults standardUserDefaults] setObject:language forKey:kJwLanguagerSaveKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        self.currentLanguage = language;
        [[NSNotificationCenter defaultCenter] postNotificationName:kJwLanguagerNotiKey object:nil userInfo:nil];
    } else {
        NSLog(@"[JwLanguager] 设置language不在languageCans中");
    }
}

/// 获取当前语言对应的值
- (NSString *)valueLanguageWithKey:(NSString *)key {
    return [self valueLanguageWithKey:key table:nil];
}

/// 获取当前语言对应的值
- (NSString *)valueLanguageWithKey:(NSString *)key table:(NSString *)table {
    if (!self.enable) {
        return NSLocalizedString(key, nil);
    }
    if (!table) {
        if (!self.languageName) {
            return key;
        } else {
            table = self.languageName;
        }
    }
    NSString *language = self.currentLanguage;
    NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj"];
    NSString *value = [[NSBundle bundleWithPath:path] localizedStringForKey:key value:nil table:table];
    
    if ([value isEqualToString:key]) {
        if (self.searchEn) {
            NSString *path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
            value = [[NSBundle bundleWithPath:path] localizedStringForKey:key value:nil table:table];
        }
    }
    return value;
}




@end
